import { Global } from "@/Global";
import { HttpHelper } from "@/lib/HttpHelper";

export class AuthService {
    static Login = async (username: string, password: string,googleCode : any): Promise<any> => {
        var data = new FormData();
        data.append("username", username);
        data.append("password", password);
        data.append("googleCode", googleCode);

        var ret = await HttpHelper.postFormData("/Auth/Login", data);
        return JSON.parse(ret);
    }

    static GetMenus = async (): Promise<any> => {
        var ret = await HttpHelper.get("/Auth/GetMenus", null);
        return JSON.parse(ret);
    }

    static ModifyPassword = async (oldPwd: string, newPwd: string): Promise<void> => {
        var body = new FormData();
        body.append("oldPwd", oldPwd);
        body.append("newPwd", newPwd);

        await HttpHelper.postFormData("/Auth/ModifyPassword", body);
    }

    static refreshToken = async () => {
        try {
            if (Global.UserInfo.Token) {
                var tokenObj = JSON.parse(await HttpHelper.get("/Auth/RefreshToken", null));

                Global.UserInfo.Token = "Bearer " + tokenObj.token;
                localStorage.setItem("userinfo", JSON.stringify(Global.UserInfo));
                console.log("成功刷新token");
            }
        } catch (err: any) {
            if (err && err.statusCode == 401) {
                Global.UserInfo.Token = <any>null;
                localStorage.removeItem("userinfo");
                location.href = "/#/login";
            }
            console.error("token刷新异常", err);
        }
        finally {
            window.setTimeout(AuthService.refreshToken, 30000);
        }
    }
}